﻿using MediatR;
using MS.BasicData.Infrastructure;
using MS.BasicData.Infrastructure.IBaseRepository;
using System.ComponentModel.DataAnnotations;

namespace MS.BasicData.Read.API.Applications.Products
{
    public class DeleteProductRequestHandler : IRequestHandler<DeleteProductRequestModel, ApiRestult>
    {
        private readonly IProductBaseRepository _productBaseRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="productBaseRepository"></param>
        public DeleteProductRequestHandler(IProductBaseRepository productBaseRepository)
        {
            _productBaseRepository = productBaseRepository;
        }
        public async Task<ApiRestult> Handle(DeleteProductRequestModel request, CancellationToken cancellationToken)
        {
            ApiRestult restult = new ApiRestult()
            {
                isSuc = true,
                Code = Restult.Success,
                Message = "溯源商品信息删除成功"
            };
            try
            {
                var list = await _productBaseRepository.GetAll(a => a.ProductId == request.ProductId);
                if(list == null)
                {
                    restult.isSuc = false;
                    restult.Code = Restult.Fail;
                    restult.Message = "溯源商品信息删除失败，信息不存在";
                    return restult;
                }
                list.IsDeleted = true;
                await _productBaseRepository.UpdateAsync(list);
            }
            catch (Exception ex)
            {
                restult.isSuc = false;
                restult.Code = Restult.Fail;
                restult.Message = "溯源商品信息删除失败";
            }
            return restult;
        }
    }


    public class DeleteProductRequestModel : IRequest<ApiRestult>
    {
        /// <summary>
        /// 产品主键Id
        /// </summary>
        public int ProductId { get; set; }
    }
}
